#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Author		: KennyLee
# Created		: 2016-08-11
# Depends	    : BeautifulSoup4

from sys import argv, exit
from urllib import urlopen, urlretrieve

try:
    from bs4 import BeautifulSoup as Soup
except ImportError:
    Soup = None
    exit("""You need beautifulsoup4!
                install it from https://www.crummy.com/software/BeautifulSoup/
                or run pip install beautifulsoup4.""")


def get_version():
    version = 8
    if len(argv) > 1 and argv[1]:
        n = None
        try:
            n = int(argv[1])
        except ValueError:
            pass
        if n and n > 6:
            version = n
    return version


tomcat_mirrors = 'https://mirrors.tuna.tsinghua.edu.cn'

soup = Soup(urlopen('http://tomcat.apache.org/download-%i0.cgi' % get_version()), "html.parser")
latest_version = soup.select('#content > h3')[4].get_text()
# print latest_version

if latest_version:
    url = "%s/apache/tomcat/tomcat-%i/v%s/bin/apache-tomcat-%s.tar.gz" % \
          (tomcat_mirrors, get_version(), latest_version, latest_version)
    urlretrieve(url, "apache-tomcat-%s.tar.gz" % latest_version)
else:
    print('cant find latest version.')
